package com.lanhe.common.xss;

import com.alibaba.fastjson2.JSON;
import com.lanhe.common.constant.ConstantsRedis;
import com.lanhe.common.core.domain.AjaxResult;
import com.lanhe.common.utils.jwt.JwtHelper;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class JwtFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求传来的token
        String token = request.getHeader("Authorization");
        // 验证token
        Claims claims = JwtHelper.verifyJwt(token);

        if (claims == null) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(AjaxResult.warn(ConstantsRedis.CHECK_GET_MORE_DATA_TIP)));
        } else {
            // 存储解析的jwt信息
            servletRequest.setAttribute(ConstantsRedis.AUTHORIZATION_DATA, claims);
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void destroy() {

    }
}
